const app = getApp()
const api = require('../../api/api')
const util = require('../../utils/js/util')
Page({
  data: {
    safeToBottom: util.getSafeToBottom(),
    userInfo: null,
    bannerList: [], // banner列表
    tipList: [], // 大喇叭列表
    inviteTop: [], // 邀请排行榜
    moneyTop: [], // 收入排行榜
    qrcode: '', // 二维码
    trade: { // 代理商工会
      msg: '',
      list: [],
      page: 1,
      status: 'loading'
    },
    pop: {
      show: false,
      node: false
    },
    shareimg: '',
    sharetitle: '',
  },
  async onLoad(options) {
    options?.id && (app.globalData.inviteUserId = options.id)
    await app.login()
    const globalUserInfo = app.globalData.userInfo
    if (Array.isArray(globalUserInfo) && globalUserInfo.length === 0) {
      const env = wx.getAccountInfoSync().miniProgram.envVersion
      const domain = ['develop', 'trial'].includes(env) ? 'https://szb.demo-dev.cn' : env == 'release' ? 'https://mp.zhisuwork.com' : ''
      // 游客身份
      this.setData({
        userInfo: {
          code: '',
          isauth: 0,
          role: 'tourist',
          avatar: `${domain}/assets/img/avatar.png`,
          nickname: '点击注册/登录',
          invite_num: '0',
          success_invite_num: '0',
          invite_money: '0',
          pay_invite_money: '0',
          onjob_money: '0',
          pay_onjob_money: '0',
        }
      })
    } else {
      // 工友或代理商
      this.setData({ userInfo: globalUserInfo })
    }
    this.getshareconfig()
    this.getBanner()
    this.getTipsList()
    if (globalUserInfo.role == 'agent') {
      // 代理商获取工会列表
      this.getrade()
    } else {
      // 工友或游客获取排行榜
      this.getTopList()
    }
    options?.id && wx.navigateTo({ url: '../perfectInfo/index' })
  },
  // 获取分享配置
  async getshareconfig() {
    const res = await api.getCodeConfig()
    this.setData({ shareimg: res.inviteimg, sharetitle: res.invitetext })
  },
  // 点击工会列表
  async goto({ currentTarget: { dataset: { id } } }) {
    wx.navigateTo({
      url: `../resume/index?id=${id}`
    })
  },
  // 获取工会
  async getrade() {
    const { trade: { list, page } } = this.data
    const res = await api.getInviteList({ page })
    this.setData({
      trade: {
        msg: res.msg,
        list: res.data.current_page == 1 ? res.data.data : list.concat(res.data.data),
        status: res.data.last_page == 0 ? 'nodata' : res.data.last_page > res.data.current_page ? 'loading' : 'tobottom',
        page: res.data.current_page
      }
    })
    console.log(this.data.trade);
    
  },
  // 点击头像
  avatarTap(e) {
    const env = wx.getAccountInfoSync().miniProgram.envVersion
    const domain = ['develop', 'trial'].includes(env) ? 'https://szb.demo-dev.cn' : env == 'release' ? 'https://mp.zhisuwork.com' : ''
    wx.uploadFile({
      url: `${domain}/api/common/upload`,
      filePath: e.detail.avatarUrl,
      name: 'file',
      header: { "token": app.globalData.userInfo.token },
      success: async res1 => {
        if (res1.statusCode === 200 && res1.errMsg === "uploadFile:ok") {
          const res2 = JSON.parse(res1.data)
          if (res2.code === 1) {
            await api.profile({ avatar: res2.data.fullurl })
            this.setData({ 'userInfo.avatar': res2.data.fullurl })
            util.toast('头像修改成功')
          } else {
            util.toast(res2.msg)
          }
        } else {
          util.toast('上传失败，网络错误')
        }
      }
    })
  },
  // 喇叭列表点击
  tipsTap({ currentTarget: { dataset: { item } } }) {
    item.url && wx.navigateTo({ url: `${item.url}&from=tip` })
  },
  // 点击邀请数据
  gotolist() {
    if(this.data.userInfo.role == 'tourist') return
    wx.navigateTo({ url: '../inviteList/index' })
  },
  // 点击右边箭头和简历完成度
  rightTap() {
    wx.navigateTo({ url: '../perfectInfo/index' })
  },
  // 弹窗动画结束
  transitionEnd() {
    this.data.pop.show || this.setData({ 'pop.node': false })
  },
  // 点击二维码
  async tapQrcode() {
    this.setData({ qrcode: await api.getUserQRCode() })
    this.setData({ 'pop.node': true })
    this.createSelectorQuery().select('#popup').boundingClientRect().exec(() => {
      this.setData({ 'pop.show': true })
    })
  },
  // 关闭弹窗
  close() {
    this.setData({ 'pop.show': false })
  },
  // 获取banner
  async getBanner() {
    this.setData({ bannerList: await api.getBanner() })
  },
  // banner点击
  bannerTap({ currentTarget: { dataset: { item } } }) {
    wx.navigateTo({ url: `${item.url}&from=banner` })
  },
  // 获取大喇叭列表
  async getTipsList() {
    this.setData({ tipList: await api.getTipsList() })
  },
  // 获取排行榜
  async getTopList() {
    const res = await api.getTopList()
    this.setData({ inviteTop: res.invite, moneyTop: res.money })
  },
  onReachBottom() {
    if (this.data.userInfo.role == 'agent') {
      this.setData({ page: this.data.trade.page + 1 })
      this.getrade()
    }
  },
  onShareAppMessage(e) {
    return {
      title: this.data.sharetitle,
      path: `/pages/index/index?id=${this.data.userInfo.id}`,
      imageUrl: this.data.shareimg
    }
  },
});